//------------------------------------------------------------------------------
// <copyright file="HeroesCollectionControl.xaml.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DotBeer.Business.Entities;
using DAnton.Utilities.Extensions;
using DotBeer.Business.Components;
using System.Collections.Specialized;

namespace DotBeer.UI.WPFClient
{
    /// <summary>
    /// Interaction logic for HeroesCollectionControl.xaml
    /// </summary>
    public partial class HeroesCollectionControl : UserControl, IOptionsControl
    {
        #region private members

        List<string> filesToDelete = new List<string>();
        IList<HeroTavern> heroesCopy;

        HeroesCollection heroesCollection;
        TavernsCollection tavernsCollection;

        bool changesSaved = true;

        #endregion

        #region constructors

        public HeroesCollectionControl()
        {
            InitializeComponent();

            try
            {
                this.heroesCollection = HeroesCollectionComponent.Load();
                this.heroesCollection.Heroes.CollectionChanged += new NotifyCollectionChangedEventHandler(Heroes_CollectionChanged);

                foreach(HeroTavern hero in this.heroesCollection.Heroes)
                    hero.PropertyChanged += new PropertyChangedEventHandler(hero_PropertyChanged);

                this.DataContext = this.heroesCollection.Heroes;
                this.heroesCopy = this.heroesCollection.Heroes.Clone();
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show(String.Format("Error occured while loading heroes collection: \n{0}", ex.Message), "Error");
            }

            try
            {
                this.tavernsCollection = TavernsCollectionComponent.Load();
                this.ComboBoxTaverns.ItemsSource = this.tavernsCollection.TavernsHero;
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show(String.Format("Error occured while loading taverns collection: \n{0}", ex.Message), "Error");
            }
        }

        #endregion

        #region properties

        private HeroTavern Hero
        {
            get
            {
                if (this.ListViewHeroes.SelectedItem != null)
                    return (HeroTavern)this.ListViewHeroes.SelectedItem;
                else
                    return null;
            }
        }

        #endregion

        #region public methods

        #region IOptionsControl Members

        public bool Save()
        {
            bool result = true;

            try
            {
                HeroesCollectionComponent.Save(this.heroesCollection);
                this.changesSaved = true;
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show(String.Format("Error occured while saving heroes collection: \n{0}", ex.Message), "Error");
                result = false;
            }

            foreach (string filePath in this.filesToDelete)
            {
                try
                {
                    File.Delete(filePath);
                }
                catch(Exception ex)
                {
                    CustomMessageBox.Show(String.Format("Error occured while deleting file: \n{0}", ex.Message), "Error");
                }
            }

            return result;
        }

        public void Cancel()
        {
            if (!this.changesSaved)
            {
                this.heroesCollection.Heroes.Clear();
                this.heroesCollection.Heroes.AddRange(this.heroesCopy);
            }
        }

        #endregion

        #endregion

        #region private methods

        #region user actions

        private void ListView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete && this.ListViewHeroes.SelectedItem != null)
            {
                if (CustomMessageBox.Show("Are you sure?", "Confirm delete", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    HeroTavern hero = Hero;

                    if (hero != null)
                    {
                        ((ObservableCollection<HeroTavern>)this.ListViewHeroes.ItemsSource).Remove(hero);
                        this.filesToDelete.Add(hero.ImagePath);
                    }
                }
            }
        }

        private void ButtonAdd_Click(object sender, RoutedEventArgs e)
        {
            WindowAddNewObject winNew = new WindowAddNewObject("hero");

            if (winNew.ShowDialog() == true)
            {
                string newHeroName = winNew.NewObjectName.Trim();

                if (this.heroesCollection.Heroes.SingleOrDefault(hero => hero.Name.ToUpper() == newHeroName.ToUpper()) == null)
                {
                    HeroTavern heroTavern = new HeroTavern()
                    {
                        Name = newHeroName
                    };

                    this.heroesCollection.Heroes.Add(heroTavern);
                    this.heroesCollection.Heroes.Sort(hero => hero.Name, ListSortDirection.Ascending);

                    this.ListViewHeroes.SelectedItem = heroTavern;
                    this.ListViewHeroes.ScrollIntoView(heroTavern);
                }
                else
                    CustomMessageBox.Show(String.Format("Hero: \"{0}\" is already on the list.", newHeroName), 
                                        "Error");
            }
        }

        private void ButtonImagePath_Click(object sender, RoutedEventArgs e)
        {
            string fileName = Dialogs.OpenImageFileDialog();

            if (fileName != null && this.ListViewHeroes.SelectedItem != null)
            {
                HeroTavern hero = (HeroTavern)this.ListViewHeroes.SelectedItem;
                hero.ImagePath = fileName;
            }
        }

        #endregion

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !NumericValidation.IsNumeric(e.Text);
        }

        private void hero_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.changesSaved = false;
        }

        private void Heroes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                this.changesSaved = false;
                this.heroesCollection.Heroes[e.NewStartingIndex].PropertyChanged += new PropertyChangedEventHandler(this.hero_PropertyChanged);
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                this.changesSaved = false;
                ((HeroTavern)e.OldItems[0]).PropertyChanged -= this.hero_PropertyChanged;
            }
        }

        #endregion
    }
}
